<template>
  <div class="fittedCurve">
    <!-- 图形 -->
    <div class="toolbox">
      <el-checkbox-group v-model="checkList">
        <el-checkbox :label="$t('page.curve')" />
      </el-checkbox-group>
      <el-radio-group v-model="radioItem">
        <el-radio label="拟合">{{ $t('page.fitting')}}</el-radio>
        <el-radio label="优化">{{ $t('page.optimize') }}</el-radio>
      </el-radio-group>
    </div>
    <div class="chart"
          v-for="(chart,index) in allStepOneCharts"
          :key="index">
      <wave-chart 
        :id="'logStepOne1'+index"
        :data='chart'
        @shotImg="shotImg"
      ></wave-chart>
    </div>
  </div>
</template>

<script>
import waveChart from '@/components/WaveChart'
import { COLORLIST } from '@/utils/variate'
import { setGrapDataTwo } from '@/utils/setGraphicData'
export default {
  components: {
    waveChart
  },
  props: {
    // 原始数据
    originalData1: {
      type: Array,
      default: () => []
    },
    // 拟合数据
    originalData2: {
      type: Array,
      default: () => []
    },
    // 优化后的数据
    originalData3: {
      type: Array,
      default: () => []
    },
    // echarts的标题
    title: {
      type: String,
      default: ''
    },
    resultValue: {
      type: Object,
      default: () => {}
    },
    // 标识线数据
    dissociation: {
      type: Array,
      default: () => [0]
    }
  },
  data() {
    return {
      allStepOneCharts: [],  // 渲染需要的数据
      originalData: [], // 处理好的数据
      standby: [],  // 备用处理好的数据
      waveName: [], // key的数组 
      checkList: ['曲线'], 
      radioItem: '拟合'
    }
  },
  methods: {
    initCharts() {
      const { key = [], data1 = []} = this.resultValue
      this.allStepOneCharts = []
      this.originalData.forEach((item) => {
        let chartsOption = {
          title: {
            text: '',
          },
          animation: false,
          color: COLORLIST,
          tooltip: {
            trigger: 'axis',
            // 自定义tootip 
            formatter: (params) => {
              let str = `<p style="text-align: center;margin:0;">${ params[0].axisValueLabel }</p><br />`
              params.forEach((item, index) => {
                let name = ''
                const isShowHole = data1.some(sub => sub)
                // 判断是否输入浓度
                if(isShowHole) {
                  if(item.seriesName.indexOf('拟合') > -1) {
                    // const arr = this.beforeLable.filter(item => +item)
                    const str = item.seriesName.slice(2)
                    const index = key.findIndex(sub => sub === str)
                    name = `拟合${data1[index]}`
                  }else if(item.seriesName.indexOf('优化') > -1) {
                    // const arr = this.beforeLable.filter(item => +item)
                    const str = item.seriesName.slice(2)
                    const index = key.findIndex(sub => sub === str)
                    name = `优化${data1[index]}`
                  } else {
                    let i = this.waveName.findIndex(key => key === item.seriesName)
                    name =  data1[i]
                  }
                } else {
                  name = item.seriesName
                }

                str += `<div 
                  style="width:100%;
                  padding:0 10px;
                  text-align: left;
                  ">
                    <span 
                      style="display:inline-block;
                      margin-right:5px;
                      border-radius:50%;
                      width:10px;
                      height:10px;
                      margin-left:5px;
                      background-color: 
                      ${item.seriesName.indexOf('拟合') > -1 
                      || item.seriesName.indexOf('优化') > -1 
                      ? '#000' : this.test(item.seriesName, index)}">
                    </span>
                    <span>
                    ${name}：${item.value}
                </div>`
              })
              return str
            }
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            align: 'left',
            // left: 'right',
            right: '20',
            top: '60',
            data: [],
            itemGap: 20,
            icon: 'circle',
            itemWidth: 20,
            padding: [ 0, 0, 10, 0 ],
            width: "70%",
            textStyle: {
              fontSize: 20
            },
            formatter: (name) => {
              const isShowHole = data1.some(sub => sub)
              if(isShowHole) { 
                if(name.indexOf('拟合') > -1) {
                  // const arr = this.beforeLable.filter(item => +item)
                  const str = name.slice(2)
                  const index = key.findIndex(item => item === str)
                  return `拟合${data1[index]}`
                } else if(name.indexOf('优化') > -1) {
                  const str = name.slice(2)
                  const index = key.findIndex(item => item === str)
                  return `优化${data1[index]}`
                } else {
                  const index = this.waveName.findIndex(item => item === name)
                  return data1[index]
                }
              } else {
                return name
              }
            }
          },
          grid: {
            left: '3%',
            right: '13%',
            bottom: '15%',
            containLabel: true,
          },
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: "value",
            minorTick: {
              show: true,
            },
            axisLine: {
              onZero: false,
            },
            axisTick: {
              show: true,
              inside: true,
            },
            axisLabel: {
              formatter: "{value}",
              textStyle: {
                fontWeight: 700,
                color: "#4c4c4c",
                fontSize: 20,
              },
            },
            splitLine: {
              show: false,
            },
          },
          yAxis: {
            type: "value",
            splitNumber: 4,
            minorTick: {
              show: true,
            },
            axisTick: {
              show: true,
              inside: true,
            },
            axisLine: {
              onZero: false,
              show: true,
              lineStyle: {
                color: "black",
              },
            },
            axisLabel: {
              formatter: "{value}",
              textStyle: {
                fontWeight: 700,
                color: "#4c4c4c",
                fontSize: 20,
              },
            },
            splitLine: {
              show: false,
            },
          },
          series: [],
        }
        chartsOption.series = []
        let num = 0
        for (let i in item) {
          if (i !== 'time') {
            let chartSeries = {
              name: this.waveName[num],
              type: 'line',
              // smooth: true,
              itemStyle: {
                color: this.waveName[num].indexOf('拟合') > -1 || this.waveName[num].indexOf('优化') > -1 ? '#000000' : ''
              },
              lineStyle: {
                width: 2.2
              },
              markLine: {
                symbol: 'none',
                lineStyle: {
                  normal: {
                    color: '#000',
                  },
                },
                data: [
                  {
                    xAxis: this.dissociation[0],
                  },
                ],
                label: {
                  normal: {
                    formatter: this.dissociation[0],
                  },
                },
              },
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
            }
            // echarts 标题
            chartsOption.title.text = this.title

            chartsOption.legend.data = this.waveName
            chartsOption.series.push(chartSeries)
            num++
          }
        }
        this.allStepOneCharts.push(chartsOption)

      })
    },

    // 拟合展示 
    test(name, index) {
      if(name.indexOf('拟合') > -1 && this.checkList.includes('拟合')) {
        if(this.checkList.length > 1) {
          return '#000'
        } else {
          return COLORLIST[index]
        }
      } else {
        return COLORLIST[index]
      }
    },

    // 处理图形数据
    setSoomth(originalData = {}, mergeData = {}, optimizeData = {} ) {
      const result = setGrapDataTwo(originalData, mergeData, optimizeData);
      this.originalData = result.resultList;
      this.waveName = result.keyList;
      this.standby = this.originalData
      
      // const key1 = originalData instanceof Object && Object.keys(originalData).filter(item => item !== 'time')
      // const key2 = mergeData instanceof Object && Object.keys(mergeData).map(item => item !== 'time' && `拟合${item}`).filter(Boolean)
      // const key3 = optimizeData instanceof Object && Object.keys(optimizeData).map(item => item !== 'time' && `优化${item}`).filter(Boolean)
      // const keysList = [].concat(key1, key2, key3).filter(item => typeof item === 'string')
      
      // let obj1 = {}
      // for (const k in mergeData) {
      //   if(k !== 'time' ) {
      //     obj1[`拟合${k}`] = mergeData[k]
      //   } else {
      //     obj1['time'] = mergeData[k]
      //   }
      // }
      // let obj2 = {}
      // for (const k in optimizeData) {
      //   if(k !== 'time' ) {
      //     obj2[`优化${k}`] = optimizeData[k]
      //   } else {
      //     obj2['time'] = optimizeData[k]
      //   }
      // }
      // this.waveName = keysList
      // this.originalData = [{...originalData, ...obj1, ...obj2}]
    },
    // 返回生成图片base64
    shotImg(url) {
      this.$emit('showImg', url)
    }
  },
  watch: {
    originalData1: {
      handler() {
        this.$nextTick( async () => {
          await this.setSoomth(this.originalData1[0], this.originalData2[0])
          this.initCharts()
        })
      },
      deep: true,
      immediate: true
    },
    radioItem: {
      handler(value) {
        this.waveName = []
        if(this.checkList.includes('曲线')) {
          this.setSoomth(this.originalData1[0], value === '拟合' && this.originalData2[0], value === '优化' && this.originalData3[0])
        } else {
          this.setSoomth({}, value === '拟合' && this.originalData2[0], value === '优化' && this.originalData3[0])
        }
        this.initCharts()
      },
      deep: true
    },
    // 监听多选变化
    checkList: {
      handler(value) {
        this.waveName = []
        if(value.includes('曲线')) {
          this.setSoomth(this.originalData1[0], this.radioItem === '拟合' && this.originalData2[0], this.radioItem === '优化' && this.originalData3[0])
        } else {
          this.setSoomth({}, this.radioItem === '拟合' && this.originalData2[0], this.radioItem === '优化' && this.originalData3[0])
        }
        this.initCharts()
      },
      deep: true
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color:#409eff;
    border-color: #409eff;
  }
  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
    border-color: #fff;
  }
  .el-checkbox__input.is-disabled+span.el-checkbox__label {
    color: #409eff;
  }
}
.fittedCurve {
  display: flex;
  flex-direction: column;
  .toolbox {
    display: flex;
    align-items: center;
    margin-bottom: 40px;
    ::v-deep {
      .el-radio-group {
        margin-left: 20px;
      }
    } 
  }
}
</style>